package cn.bsuc.crm.util;

import cn.bsuc.crm.entity.User;
import com.alibaba.fastjson2.JSON;
import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Date;


/**
 * @author : zhuoyuan
 * @date : 2022/10/8 10:37
 * @description :
 */
public class JwtUtils {
    private static final long TIME = 1000 * 60 * 60;
    private static final String SIGNATURE = "admin";

    /**
     * 根据 username 生成 token
     * @return
     */
    public static String createToken(String username) {
        JwtBuilder jwtBuilder = Jwts.builder();
        String jwtToken = jwtBuilder
                // header
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setIssuedAt(new Date())
                // payload
                .claim("username", username)
//                .setExpiration(new Date(System.currentTimeMillis() + TIME))
//                .setId(UUID.randomUUID().toString())
                // signature
                .signWith(SignatureAlgorithm.HS256, SIGNATURE)
                .compact();
        return jwtToken;
    }

    /**
     * 根据user对象生成token
     * @param user
     * @return
     */
    public static String createTokenByUser(User user) {
        String json = JSON.toJSONString(user);
        return JwtUtils.createToken(json);
    }


    /**
     * 验证token是否有效
     * @param token
     * @return
     */
    public static boolean checkToken(String token) {
        if (token == null) {
            return false;
        }
        try {
           Jwts.parser().setSigningKey(SIGNATURE).parseClaimsJws(token);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 根据token获得username
     * @param token
     * @return
     */
    public static String getUsernameByToken(String token){
        if(StringUtils.isEmpty(token)) return "";
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(SIGNATURE).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String)claims.get("username");

    }
    /**
     * 根据token获得 User 对象
     * @param token
     * @return
     */
    public static User getUserByToken(String token){
        String userJson = JwtUtils.getUsernameByToken(token);
        return JSON.parseObject(userJson,User.class);
    }

}
